<template>
  <div class="account">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      class="demo-ruleForm"
      required
    >
      <el-form-item prop="account" size="large">
        <el-input v-model="ruleForm.account" placeholder="请输入账户" />
      </el-form-item>
      <el-form-item prop="pass" size="large">
        <el-input
          v-model="ruleForm.pass"
          type="password"
          placeholder="请输入密码"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { reactive, ref } from 'vue';
import { useStore } from 'vuex';
import type { ElForm } from 'element-plus';
import { ElMessage } from 'element-plus';
import localCache from '@/utils/cache';

export default defineComponent({
  setup() {
    const cacheName = localCache.getCache('name') ?? '';
    const cachePassword = localCache.getCache('password') ?? '';

    const ruleForm = reactive({
      // TODO: 优化保存密码, 没有点保存密码是,不填充密码到input中
      account: cacheName,
      pass: cachePassword
    });

    const rules = reactive({
      account: [
        {
          required: true,
          message: '必须是填写账户',
          trigger: 'blur'
        },
        {
          pattern: /^[a-z0-9]{6,20}$/,
          message: '必须是6~20个字母或者数字',
          trigger: 'blur'
        }
      ],
      pass: [
        {
          required: true,
          message: '必须填写密码',
          trigger: 'blur'
        },
        {
          pattern: /^[a-z0-9]{3,}$/,
          message: '必须是3位以上数字',
          trigger: 'blur'
        }
      ]
    });

    const store = useStore();
    const ruleFormRef = ref<InstanceType<typeof ElForm>>();
    const accountLoginAction = (isKeep: boolean) => {
      ruleFormRef.value?.validate((valid) => {
        if (valid) {
          const name = ruleForm.account;
          const password = ruleForm.pass;

          if (isKeep) {
            localCache.setCache('name', name);
            localCache.setCache('password', password);
          }
          store.dispatch('login/accountLoginAction', { name, password });
          ElMessage.success('登录成功');
        } else {
          ElMessage.error('登录失败');
          return false;
        }
      });
    };
    return {
      ruleForm,
      rules,
      ruleFormRef,
      accountLoginAction
    };
  }
});
</script>

<style scoped></style>
